package com.hqw.mindanews;

import cn.bmob.v3.exception.BmobException;
import cn.bmob.v3.listener.LogInListener;
import cn.pedant.SweetAlert.SweetAlertDialog;

import com.hqw.mindanews.application.SysApplication;
import com.hqw.mindanews.bean.User;
import com.hqw.mindanews.utils.Toastor;

import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;

public class LoginActivity extends Activity implements OnClickListener{
	
	TextView mBack;
	TextView mRegesit;
	private Toastor mToastor;   
	private Button mLonginBtn;
	private EditText mPhone;
	private EditText mPassWord;
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		// TODO Auto-generated method stub
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_login);
		initView();
		SysApplication.getInstance().addActivity(this);
	}

	private void initView() {
		mToastor = new Toastor(this);
		mBack = (TextView) findViewById(R.id.activity_back);
		mRegesit = (TextView) findViewById(R.id.account_regist);
		mBack.setOnClickListener(this); 
		mRegesit.setOnClickListener(this);
		mLonginBtn = (Button) findViewById(R.id.login_btn);
		mLonginBtn.setOnClickListener(this);
		mPassWord = (EditText) findViewById(R.id.user_password);
		mPhone = (EditText) findViewById(R.id.user_account);
		
	}
	private void loginUser() {
		String accuont = mPhone.getText().toString();
		String password = mPassWord.getText().toString();
		User.loginByAccount(LoginActivity.this, accuont, password, new LogInListener<User>() {

			@Override
			public void done(User user, BmobException ex) {
				if (user!=null) {
					Intent it = new Intent(LoginActivity.this, MainActivity.class);
					startActivity(it);
					LoginActivity.this.finish();
				}else {
				String exs =	ex.getMessage();
				new SweetAlertDialog(LoginActivity.this).setContentText(exs).show();
				}
				
			}
		});
		
	}

	@Override
	public void onClick(View v) {
		switch (v.getId()) {
		case R.id.activity_back:
			mToastor.showLongToast("返回上一级");
			LoginActivity.this.finish();
			break;
		case R.id.account_regist:
			mToastor.showLongToast("注册账户");
			Intent it = new Intent(LoginActivity.this, RegistActivity.class);
			startActivity(it);
			break;
			case R.id.login_btn :
				String accuont = mPhone.getText().toString();
				String password = mPassWord.getText().toString();
				
				if (accuont.equals("")||password.equals("")) {
					new SweetAlertDialog(this).setContentText("选项不能为空哦").show();
					return;
				}
				loginUser();
				
		default:
			break;
		}
		
	}
}
